package com.example.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Aspect
@Component
public class RegisterAspect {
	
	private final static Logger log = LoggerFactory.getLogger(RegisterAspect.class);
	
	/**
	 * 在控制器上进行切点配置
	 */
	@Pointcut("execution(public * com.example.controllers.*.*(..))")
	public void ctrlLog(){}
	
	/**
	 * 在service层配置切点
	 */
	@Pointcut("execution(public * com.example.service.*.*(..))")
	public void serviceLog(){}
	
	/**
	 * 可以在此处执行参数日志记录
	 * @param joinpoint
	 */
	@Before("ctrlLog()")
	public void doBeforeOnCtrl(JoinPoint joinpoint){
		
		
		ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request=attributes.getRequest();
		//url
		log.info("url={}",request.getRequestURL());
		//method
		log.info("method={}",request.getMethod());
		//args
		log.info("args={}",joinpoint.getArgs());
		//class_method
		log.info("class_method={}",joinpoint.getSignature().getDeclaringTypeName()+"."+joinpoint.getSignature().getName());
		
		
	}
	
	@Before("serviceLog()")
	public void doBeforeLogOnService(){
		
		 log.info("before-------------------------------->service");
	}
	
	
	/**
	 * service层返回之前的切面
	 */
	@AfterReturning(pointcut="serviceLog()",returning="object")
	public void beforeServiceReturn(Object object){

		log.info("response={}",object.toString());
	}
	
	/**
	 * 异常通知
	 */
	@AfterThrowing(value="ctrlLog()",throwing="e")
	public void doAfterThrow(JoinPoint joinpoint,Exception e){
		
		log.info("Exception={}",e.getMessage());
		
	}
	
		

}
